﻿using UnityEngine;
using System.Collections.Generic;

namespace GameDesigner
{
    public abstract class StateMachineView : MonoBehaviour
    {
        public StateMachineCore stateMachine;
#if UNITY_EDITOR
        [HideInInspector]
        public StateMachineCore editStateMachine;
        internal int editStateMachineId = -1;
#endif
        [SerializeField] private List<string> clipNames;
        public List<string> ClipNames { get => clipNames ??= new List<string>(); set => clipNames = value; }
        public virtual Transform Parent { get; }

        public virtual void Init()
        {
        }

        public virtual void OnDestroy()
        {
            stateMachine.OnDestroy();
        }

#if UNITY_EDITOR
        public virtual void EditorInit(Transform root) { }

        public void OnValidate()
        {
            OnScriptReload();
        }

        public virtual void OnScriptReload()
        {
            if (stateMachine == null)
                return;
            stateMachine.View = this;
            stateMachine.OnScriptReload(this);
            stateMachine.Id.Value = -1;
            for (int i = 0; i < stateMachine.SubStateMachines.Length; i++)
                stateMachine.SubStateMachines[i].Id.Value = i;
            UpdateEditStateMachine(editStateMachineId);
        }

        public virtual void UpdateEditStateMachine(int editStateMachineId)
        {
            this.editStateMachineId = editStateMachineId;
            if (editStateMachineId == -1)
                editStateMachine = stateMachine;
            else if (editStateMachineId < stateMachine.SubStateMachines.Length)
                editStateMachine = (StateMachineCore)stateMachine.SubStateMachines[editStateMachineId];
        }

        public virtual float GetAnimClipLength(StateAction action) => 0f;
#endif
    }
}